package com.wkck.controller;

import cn.dustlight.captcha.annotations.CodeValue;
import cn.dustlight.captcha.annotations.SendCode;
import com.wkck.domain.LoginUser;
import com.wkck.service.LoginService;
import com.wkck.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/logins")
@Slf4j
public class LoginController {

    /**
     * 响应到img标签
     */

    @Autowired
    private HttpServletResponse httpServletResponse;

    /**
     * 简易：用来保存验证码
     */

    private String code;

    /**
     * 登录业务
     */

    @Autowired
    private LoginService loginService;

    /**
     * 登录验证码需求
     */

//    @GetMapping("/createCode")
//    @ResponseBody
//    public void setCode() throws IOException {
//        // 利用 hutool 工具，生成验证码图片资源
//        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 60, 4, 5);
//        code = captcha.getCode();
//        System.out.println(code+"1");
//        // 将验证码图片的二进制数据写入【响应体 response 】
//        captcha.write(httpServletResponse.getOutputStream());
//        log.info("本次验证码生效成功" + captcha);
//    }

    @RequestMapping("/captcha")
    @SendCode // 生成随机字符图像验证码并发送
    public void captcha(@CodeValue String code) {
        // 在此处进行自定义的业务，验证码的生成、发送与储存已由注解 '@SendCode' 完成。
        this.code = code;
    }

    /**
     * 得到验证码接口
     */

    @GetMapping("/getCode")
    @ResponseBody
    public Result getCode(){
        Integer codeSu = this.code == null ? 404 : Code.CREATE_OK;
        String msg = this.code == null ? "请重新生成验证码" : Msg.CREATE_OK;
        log.info("本次验证码是:" + this.code);
        return new Result(codeSu,this.code,msg);
    }

    /**
     * 检测用户是否存在
     * @param loginUser
     * @return
     */

    @PostMapping("/detectionExistUser")
    @ResponseBody
    public Result detectionExistUser(@RequestBody LoginUser loginUser){
        boolean save = loginService.existUser(loginUser);
        Integer code = save ? Code.SELECT_OK : Code.SELECT_ERR;
        String msg = save ? Msg.SELECT_OK : Msg.SELECT_ERR;
        return new Result(code,save,msg);
    }

    /**
     * 登录判断密码是否正确
     * @param loginUser
     * @return
     */

    @PostMapping("/checkUserPassword")
    @ResponseBody
    public Result checkUserPassword(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestBody LoginUser loginUser){
        boolean flag = loginService.checkUserPassword(loginUser);
        Integer code = flag ? Code.LOGIN_OK : Code.LOGIN_ERROR;
        String msg = flag ? Msg.LOGIN_OK : Msg.LOGIN_ERROR;
        if (flag) {
            LoginUser msgByUserName = loginService.getMsgByUserName(loginUser.getUsername());
            // 将登录用户信息保存到session中
            session.setAttribute(Const.SYSTEM_USER_SESSION, msgByUserName);
            // 保存cookie，实现自动登录
            Cookie cookie_username = new Cookie("cookie_username", loginUser.getUsername());
            // 设置cookie的持久化时间，1天
            cookie_username.setMaxAge(24 * 60 * 60);
            // 设置为当前项目下都携带这个cookie
            cookie_username.setPath("/");
            // 向客户端发送cookie
            response.addCookie(cookie_username);
        } else {
            // 删除session里面的用户信息
            session.removeAttribute(Const.SYSTEM_USER_SESSION);
            // 保存cookie，实现自动登录
            Cookie cookie_username = new Cookie("cookie_username", "");
            // 设置cookie的持久化时间，0
            cookie_username.setMaxAge(0);
            // 设置为当前项目下都携带这个cookie
            cookie_username.setPath("/");
            // 向客户端发送cookie
            response.addCookie(cookie_username);
        }
        return new Result(code,flag,msg);
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "logout",method = RequestMethod.GET)
    public void logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 删除session里面的用户信息
        session.removeAttribute(Const.SYSTEM_USER_SESSION);
        // 保存cookie，实现自动登录
        Cookie cookie_username = new Cookie("cookie_username", "");
        // 设置cookie的持久化时间，0
        cookie_username.setMaxAge(0);
        // 设置为当前项目下都携带这个cookie
        cookie_username.setPath("/");
        // 向客户端发送cookie
        response.addCookie(cookie_username);
        response.sendRedirect("/pages/main.html");
    }

    /**
     * 个人中心 -> 修改密码后返回登录界面重新登录加载信息
     * @param session
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    @RequestMapping(value = "logout1",method = RequestMethod.GET)
    public void logout1(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 删除session里面的用户信息
        session.removeAttribute(Const.SYSTEM_USER_SESSION);
        // 保存cookie，实现自动登录
        Cookie cookie_username = new Cookie("cookie_username", "");
        // 设置cookie的持久化时间，0
        cookie_username.setMaxAge(0);
        // 设置为当前项目下都携带这个cookie
        cookie_username.setPath("/");
        // 向客户端发送cookie
        response.addCookie(cookie_username);
        response.sendRedirect("/pages/login.html");
    }
}
